from datetime import datetime
from extensions import db

class Version(db.Model):
    """版本模型"""
    __tablename__ = 'versions'

    # 基本信息
    id = db.Column(db.Integer, primary_key=True)
    project_id = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=False)
    version_number = db.Column(db.String(32), nullable=False)
    asc_version_id = db.Column(db.String(100))
    status = db.Column(db.String(32), nullable=False, default='pending')  # pending/processing/success/failed
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    completed_at = db.Column(db.DateTime)
    
    # Metadata相关
    metadata_path = db.Column(db.String(256))
    release_notes = db.Column(db.Text)
    
    # 执行状态
    download_status = db.Column(db.String(32), default='pending')  # pending/processing/success/failed
    upload_status = db.Column(db.String(32), default='pending')    # pending/processing/success/failed
    error_message = db.Column(db.Text)

    # 关联关系
    project = db.relationship('Project', back_populates='versions')

    def __init__(self, **kwargs):
        """初始化版本实例"""
        super(Version, self).__init__(**kwargs)

    def __repr__(self):
        return f'<Version {self.version_number}>'

    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'project_id': self.project_id,
            'version_number': self.version_number,
            'created_at': self.created_at.isoformat(),
            'completed_at': self.completed_at.isoformat() if self.completed_at else None,
            'status': self.status,
            'error_message': self.error_message,
            'asc_version_id': self.asc_version_id,
            'metadata_path': self.metadata_path,
            'download_status': self.download_status,
            'upload_status': self.upload_status,
            'release_notes': self.release_notes
        }

    def from_dict(self, data, partial=False):
        """从字典更新属性
        
        Args:
            data: 数据字典
            partial: 是否部分更新
        """
        fields = ['project_id', 'version_number', 'asc_version_id', 'metadata_path', 'release_notes', 
                 'status', 'error_message', 'download_status', 'upload_status']
        
        for field in fields:
            if field in data:
                setattr(self, field, data[field])
            elif not partial:
                if field == 'status':
                    setattr(self, field, 'pending')
                elif field in ['download_status', 'upload_status']:
                    setattr(self, field, 'pending')
                else:
                    setattr(self, field, None)
        
        return self
